package com.zheng.hr.rpc.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.zheng.common.annotation.BaseService;

import com.zheng.hr.dao.model.HrTrain;
import com.zheng.hr.dao.mapper.HrTrainMapper;
import com.zheng.hr.dao.model.HrTrainUser;
import com.zheng.hr.rpc.api.HrDictService;
import com.zheng.hr.rpc.api.HrTrainService;
import com.zheng.common.base.BaseServiceImpl;
import com.zheng.hr.rpc.api.HrTrainUserService;
import com.zheng.oa.common.constant.enums.OaStatus;
import com.zheng.upms.dao.model.UpmsUser;
import com.zheng.upms.rpc.api.UpmsApiService;
import com.zheng.upms.rpc.api.UpmsUserService;
import com.zheng.wc.dao.model.WcNotice;
import com.zheng.wc.rpc.api.WcNoticeService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author likun
 * @since 2018-03-14
 */
@Service
@Transactional(rollbackFor = Exception.class)
@BaseService
public class HrTrainServiceImpl extends BaseServiceImpl<HrTrainMapper, HrTrain> implements HrTrainService {
    @Autowired
    private UpmsApiService apiService;
    @Autowired
    private WcNoticeService noticeService;
    @Autowired
    private HrDictService dictService;
    @Autowired
    private HrTrainUserService trainUserService;
    @Autowired
    private UpmsUserService upmsUserService;

    @Override
    public boolean insertTrain(HrTrain train, String username) throws Exception {
        train.setCtime(new Date());
        UpmsUser upmsUser = apiService.selectUpmsUserByUsername(username);
        WcNotice notice = new WcNotice();
        if (null != upmsUser) {
            notice.setCuser(upmsUser.getUserId());
            notice.setCorganization(upmsUser.getOrganizationId());
            train.setCuser(upmsUser.getUserId());
            train.setCorganization(upmsUser.getOrganizationId());
        }
        String joinInfo = train.getJoinInfo();
        List<Integer> ids = new ArrayList<>();
        if (StringUtils.isNotBlank(joinInfo)) {
            String[] joinInfoArray = joinInfo.split(",");
            for (String id : joinInfoArray) {
                ids.add(Integer.parseInt(id));
            }
        }

        boolean insert = insert(train);
        insetTrainUserId(ids, train.getId());
        //判断是否有内部讲师
        if (train.getInsideInstructor()) {
            ids.add(train.getTrainInstructorId());
        }
        //添加通知
        String type = dictService.getDictValue("培训通知", "notice_type", "1");
        String state = dictService.getDictValue("已发布", "notice_state", "1");
        notice.setType(Integer.parseInt(type));
        notice.setCtime(new Date());
        notice.setStatus(OaStatus.NORMAL.getKey());
        notice.setSendTime(new Date());
        Date beginTime = train.getBeginTime();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd hh:MM:ss");
        String time = simpleDateFormat.format(beginTime);
        notice.setTitle("培训通知(" + time + ")");
        String contend = "培训名称: " + train.getTrainName();
        //判断是否有内部讲师
        if (train.getInsideInstructor()) {
            UpmsUser instructor = upmsUserService.selectById(train.getTrainInstructorId());
            contend += "<br/>培训讲师: " + instructor.getRealname();
        } else {
            contend += "<br/>培训讲师: " + train.getTrainInstructor();
        }
        contend += "<br/>召开地点：" + train.getTrainPlace() + "<br/>培训时间：" + time + "<br/>请准时参加！";
        notice.setContent(contend);
        noticeService.insertNotice(notice, ids, Integer.parseInt(state));
        return insert;
    }

    @Override
    public boolean updateTrain(HrTrain train) throws Exception {
        HrTrain oldTrain = selectById(train);
        WcNotice notice = new WcNotice();
        notice.setCuser(oldTrain.getCuser());
        notice.setCorganization(oldTrain.getCorganization());
        String joinInfo = train.getJoinInfo();

        List<Integer> ids = new ArrayList<>();
        if (StringUtils.isNotBlank(joinInfo)) {
            String[] joinInfoArray = joinInfo.split(",");
            for (String id : joinInfoArray) {
                ids.add(Integer.parseInt(id));
            }
        }
        if (StringUtils.isNotBlank(joinInfo)) {
            EntityWrapper<HrTrainUser> entityWrapper = new EntityWrapper<>();
            entityWrapper.where("train_id=" + train.getId());
            if (trainUserService.delete(entityWrapper)) {
                insetTrainUserId(ids, train.getId());
            }
        }
        //判断是否有内部讲师
        if (train.getInsideInstructor() != null) {
            ids.add(train.getTrainInstructorId());
        }
        String type = dictService.getDictValue("会议通知", "notice_type", "1");
        String state = dictService.getDictValue("已发布", "notice_state", "1");
        notice.setType(Integer.parseInt(type));
        notice.setCtime(new Date());
        notice.setStatus(OaStatus.NORMAL.getKey());
        notice.setSendTime(new Date());
        Date beginTime = train.getBeginTime();
        if(beginTime != null){
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd hh:MM:ss");
            String time = simpleDateFormat.format(beginTime);
            notice.setTitle("培训通知变更(" + time + ")");
            String contend = "培训名称: " + train.getTrainName();
            //判断是否有内部讲师
            if (train.getInsideInstructor()) {
                UpmsUser instructor = upmsUserService.selectById(train.getTrainInstructorId());
                contend += "<br/>培训讲师: " + instructor.getRealname();
            } else {
                contend += "<br/>培训讲师: " + train.getTrainInstructor();
            }
            contend += "<br/>召开地点：" + train.getTrainPlace() + "<br/>培训时间：" + time + "<br/>请准时参加！";
            notice.setContent(contend);
            noticeService.insertNotice(notice, ids, Integer.parseInt(state));
        }
        return updateById(train);
    }

    public boolean updateTrainStatus(String ids, Integer trainStatus) throws Exception {
        String[] idArray = ids.split("-");
        for (String idStr : idArray) {
            HrTrain train = selectById(Integer.parseInt(idStr));
            train.setStatus(trainStatus);
            updateById(train);
            //todo 发送会议取消的通知
        }
        return true;
    }

    private void insetTrainUserId(List<Integer> ids, Integer trainId) {
        for (Integer id : ids) {
            HrTrainUser user = new HrTrainUser();
            user.setUserId(id);
            user.setTrainId(trainId);
            trainUserService.insert(user);
        }
    }

}
